--
-- Author:      name
-- DateTime:    2019-04-30 10:59:15
-- Description: 协议加载proto文件

local skynet = require("skynet")
local parser = require("parser")
local protobuf = require("protobuf")
local lfs = require("lfs")

local table_insert = table.insert

local ProtoLoader = class("ProtoLoader")

-- 构造
function ProtoLoader:ctor(folder_list)
    if not folder_list then 
        folder_list = {'game','gate','web', 'hall',}
    end
    self.proto_path = skynet.getenv("proto_config") or "../proto"
    self:init(self.proto_path, folder_list)    

end

-- 初始化
function ProtoLoader:init(path, dirs)
    local file_list = {}
    dirs = dirs or {}
	for _, dir in ipairs(dirs) do
		local file_path = path .. dir
        local files = self:getProtoFile(file_path)
        for k, v in pairs(files) do 
            files[k] = dir .."/"..files[k]
            table_insert(file_list, files[k])
        end        
    end	
    local files = self:getProtoFile(path)
    for k, v in pairs(files) do 
        table_insert(file_list, 1, v)
    end
    -- print("___file_list__", file_list)
    local ok, err = xpcall(parser.register, debug.traceback, file_list, path)
    if not ok then 
        error_log("__加载proto文件错误______", err)
    end           
end

function ProtoLoader:getProtoFile(path)
    local file_list = {}
    local attr = assert(lfs.attributes(path))
    if attr.mode ~= 'directory' then
        return file_list
    end   
    for f in lfs.dir(path) do
        if f:find(".proto") and f ~= '.' and f ~= '..' then
            table_insert(file_list, f)
        end
    end    
    return file_list
end

--取protobuf 中 debug.getregistry().PROTOBUF_ENV
function ProtoLoader:getProtobufEnv()
    return protobuf.get_protobuf_env()
end

--编码
function ProtoLoader:encode(msg_name, msg_body)
    -- print("+++",msg_name, msg_body)
    local ok, data = xpcall(protobuf.encode, debug.traceback, msg_name, msg_body)
    -- print("+++222")
    if not ok then
        error_log('######encode message body failed', msg_name, data)
        return
    end    
    return data
end

--解码
function ProtoLoader:decode(msg_name, msg_body)
    local ok, data = xpcall(protobuf.decode, debug.traceback, msg_name, msg_body, #msg_body)
    if not ok then
        error_log('######decode message body failed', msg_name, data)
        return
    end    
    return data
end


return ProtoLoader
